package dfs_bfs.test200;

/**
 *
 * 岛屿数量
 * @author code_yc
 * @version 1.0
 * @date 2020/7/8 11:21
 */
public class Solution1 {

    // DFS 深度优先遍历
    int r, c;

    public int numIslands(char[][] grid) {
        int res = 0;
        if (grid == null || grid.length == 0 || grid[0].length == 0) return res;
        r = grid.length;
        c = grid[0].length;
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                if (grid[i][j] == '1') {
                    res++;
                    dfs(grid, i, j);
                }
            }
        }
        return res;
    }

    private void dfs(char[][] grid, int i, int j) {
        // 首先定义一个方向
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        grid[i][j] = '2';
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < r && y >= 0 && y < c && grid[x][y] == '1') {
                dfs(grid, x, y);
            }
        }
    }

}
